package com.example.encrypt;

import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.Security;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

/**
 * DES 加密解密工具类
 * 
 * @since 2009-11-11
 * @version 1.0
 */
public class DES {

	/**
	 * 加密字符串
	 * 
	 * @param sKey
	 *            密钥
	 * @param input
	 *            待加密字符串
	 * */
	public static String Encrypt(String sKey, String input) {
		Security.addProvider(new com.sun.crypto.provider.SunJCE());

		byte[] arg0 = sKey.getBytes();

		byte[] arg1 = new byte[8];// 创建一个空的8位字节数组（默认值为0）

		// 将原始字节数组转换为8位
		for (int i = 0; i < arg0.length && i < arg1.length; i++) {
			arg1[i] = arg0[i];
		}

		Key SKey = new javax.crypto.spec.SecretKeySpec(arg1, "DES");// 生成密钥

		Cipher cph;
		try {
			cph = Cipher.getInstance("DES");
			cph.init(Cipher.ENCRYPT_MODE, SKey);
			byte[] encode = cph.doFinal(input.getBytes());

			// 每个byte用两个字符才能表示，所以字符串的长度是数组长度的两倍
			StringBuffer sb = new StringBuffer(encode.length * 2);

			for (int i = 0; i < encode.length; i++) {
				int arg2 = encode[i];
				// 把负数转换为正数
				while (arg2 < 0) {
					arg2 += 256;
				}
				// 小于0F的数需要在前面补0
				if (arg2 < 16) {
					sb.append("0");
				}
				sb.append(Integer.toString(arg2, 16));
			}
			return sb.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 解密字符串
	 * 
	 * @param sKey
	 *            密钥
	 * @param input
	 *            带解密字符串
	 * */
	public static String Dencrypt(String sKey, String input) throws Exception {
		Security.addProvider(new com.sun.crypto.provider.SunJCE());

		byte[] arg0 = sKey.getBytes();

		byte[] arg1 = new byte[8];// 创建一个空的8位字节数组（默认值为0）

		// 将原始字节数组转换为8位
		for (int i = 0; i < arg0.length && i < arg1.length; i++) {
			arg1[i] = arg0[i];
		}

		Key SKey = new javax.crypto.spec.SecretKeySpec(arg1, "DES");// 生成密钥

		Cipher cph = Cipher.getInstance("DES");
		cph.init(Cipher.DECRYPT_MODE, SKey);

		byte[] arg2 = input.getBytes();

		byte[] arg4 = new byte[arg2.length / 2];// 两个字符表示一个字节，所以字节数组长度是字符串长度除以2

		for (int i = 0; i < arg2.length; i = i + 2) {
			String arg3 = new String(arg2, i, 2);
			arg4[i / 2] = (byte) Integer.parseInt(arg3, 16);
		}
		return new String(cph.doFinal(arg4));
	}

}